<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- table-tree表格 -->
      <table-tree class="table-tree" :data="categoriesList" :columns="columns" :expand-type="false" :selection-type="false" show-index border stripe>
        <!-- 是否有效 -->
        <template slot="isOk" slot-scope="scope">
          <i class="el-icon-error" style="color: red" v-if="scope.row.cat_deleted"></i>
          <i class="el-icon-success" style="color: lightgreen" v-else></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag type="primary" size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" size="mini" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="operation" slot-scope="scope">
          <el-button type="primary" size="mini" class="el-icon-edit" @click="showEditDialog(scope.row.cat_id)">编辑</el-button>
          <el-button type="danger" size="mini" class="el-icon-delete" @click="removeById(scope.row.cat_id)">删除</el-button>
        </template>
      </table-tree>

      <!-- 添加分类对话框 -->
      <el-dialog title="添加分类" :visible.sync="addFormDialogVisible" width="width" @close="addCateDialogClosed">
        <el-form :model="addCateForm" :rules="addCateFormRules" ref="addCateFormRef" label-width="100px">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类" >
            <el-cascader :options="parentCateList" v-model="selectedKeys" :props="cascaderProps"  @change="handleChange" clearable>
            </el-cascader>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="addFormDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </div>
      </el-dialog>


      <!-- 修改分类对话框 -->
      <el-dialog title="修改分类" :visible.sync="editFormDialogVisible" width="width" @close="editCateDialogClosed">
        <el-form :model="editCateForm" :rules="editCateFormRules" ref="editCateFormRef" label-width="100px">
          <el-form-item label="分类名称" prop="cat_name">
            <!-- <el-cascader :options="parentCateList" v-model="selectedKeys" :props="cascaderProps"  @change="handleChange" clearable>
            </el-cascader> -->
            <el-input v-model="editCateForm.cat_name" placeholder=""></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button @click="editFormDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCate">确 定</el-button>
        </div>
      </el-dialog>

      <!-- <el-table :data="categoriesList" style="width: 100%">
        <el-table-column type="index" label="序号" width="width"> </el-table-column>
        <el-table-column prop="cat_name" label="分类名称" width="width"> </el-table-column>
        <el-table-column prop="cat_deleted" label="是否有效" width="width"> 
          <template slot-scope="scope">
            <i class="el-icon-error" style="color:red" v-if="scope.row.cat_deleted"></i>
            <i class="el-icon-success" style="color:lightgreen" v-else></i>
          </template>
        </el-table-column>
        <el-table-column prop="cat_level" label="排序" width="width"> 
          <template slot-scope="scope">
                <el-tag type="primary" size="mini" v-if="scope.row.cat_level==='0'">一级</el-tag>
                <el-tag type="success" size="mini" v-else-if="scope.row.cat_level===1">二级</el-tag>
                <el-tag type="warning" size="mini" v-else>三级</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="width"> 
            <el-button type="primary" size="mini" class="el-icon-edit">编辑</el-button>
            <el-button type="danger" size="mini" class="el-icon-delete">编辑</el-button>
        </el-table-column>
      </el-table> -->

      <el-pagination @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" 
      :page-sizes="[10, 15,30]" :page-size="queryInfo.pagesize" 
      layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 30,
      },
      categoriesList: [],
      total: 0,
      // 自定义tree-table列
      columns: [
        { label: "分类名称", 
        prop: "cat_name" ,
        children:'children'
        },
        {
          label: "是否有效",
          // 将当前列定义为模板列
          type: "template",
          template: "isOk",
        },
        { label: "排序", type: "template", template: "order" },
        { label: "操作", type: "template", template: "operation" },
      ],
      // 添加分类表单绑定
      addCateForm:{
        cat_name:'',
        cat_pid:0, //默认一级
        cat_level:0
      },
      // 隐藏添加分类表单
      addFormDialogVisible:false,
      // 校验规则
      addCateFormRules:{
        cat_name:[{required: true, message:'请输入分类名称', trigger: 'blur'}]
      },
      // 父级分类列表
      parentCateList:[],
      //级联选择器的配置对象
      cascaderProps:{
        label:'cat_name',
        value:'cat_id',
        expandTrigger:'hover',
        checkStrictly:true   //选择任意一个选项
      },
      //级联选择器选定的值
      selectedKeys:[],


      // 修改对话框
      editFormDialogVisible:false,
      // 修改分类表单绑定
      editCateForm:{
        cat_name:'',
        cat_pid:0, //默认一级
        cat_level:0
      },
      // 校验规则
      editCateFormRules:{
        cat_name:[{required: true, message:'请输入分类名称', trigger: 'blur'}]
      },

      


    };
  },
  created() {
    this.getCateGoriesList();
  },
  computed: {},
  methods: {
    async getCateGoriesList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类列表失败");
      }
      //提示获取权限列表成功
      this.$message.success("获取商品分类列表成功");
      this.categoriesList = res.data.result;
      this.total = res.data.total;

    },
    // 分页
    handleSizeChange(pagesize) {
      this.queryInfo.pagesize = pagesize;
      this.getCateGoriesList();
    },
    handleCurrentChange(pagenum) {
      this.queryInfo.pagenum = pagenum;
      this.getCateGoriesList();
    },
    //显示添加分类对话框
      showAddCateDialog(){
        this.getParentCateGories()
        this.addFormDialogVisible=true
      },
      // 获取父级分类
      async getParentCateGories(){
        const{data:res}=await this.$http.get('categories',{
          params:{type:2}
        })
        console.log(res)
        if(res.meta.status!==200){
         return this.$message.error('获取父级分类列表失败')
        }
        this.parentCateList=res.data
        //提示获取父级分类列表成功
        this.$message.success('获取父级分类列表成功')
      },
      // 监听级联选择器改变事件
      handleChange(){
        console.log(this.selectedKeys)
        //判断级联选择器选择是否选择父级
        if(this.selectedKeys>0){
          this.addCateForm.cat_pid=this.selectedKeys[this.selectedKeys.length-1]
          this.addCateForm.cat_level=this.selectedKeys.length
        }else{
          this.addCateForm.cat_pid=0
          this.addCateForm.cat_level=0

        }
        
      },
      // 添加分类
      addCate(){
        this.$refs.addCateFormRef.validate( async valid=>{
          if(!valid){
            return
          }
          const{data:res}=await this.$http.post('categories', this.addCateForm)
          console.log(res)
          if(res.meta.status!==201){
           return this.$message.error('失败')
          }
          //提示成功
          this.$message.success('成功')
          this.getCateGoriesList()
          this.addFormDialogVisible=false
        })
      },
      // 监听对话框关闭
      addCateDialogClosed(){
        this.$refs.addCateFormRef.resetFields()
        this.selectedKeys=[]
        this.addCateForm.cat_level=0
        this.addCateForm.cat_pid=0
      },

      //显示修改对话框
      async showEditDialog(id){
        console.log(id)
        const {data:res}=await this.$http.get(`categories/${id}`)
        if(res.meta.status!==200){
          return this.$message.error('获取失败')
        }
        console.log(res.data)
        this.editCateForm=res.data
        this.editFormDialogVisible=true
      },
      // 监听修改对话框关闭
      editCateDialogClosed(){},
      // 修改
      editCate(){
        this.$refs.editCateFormRef.validate( async valid=>{
          if(!valid){
            return
          }
          const{data:res}=await this.$http.put(`categories/${this.editCateForm.cat_id}`,{
            cat_name:this.editCateForm.cat_name
          })
          console.log(res)
          if(res.meta.status!==200){
           return this.$message.error('失败')
          }
          //提示成功
          this.$message.success('成功')
          this.getCateGoriesList()
          this.editFormDialogVisible=false
        })

      },


      // 删除
      removeById(id){
        this.$confirm('确定要删除该分类吗？','提示',{
          confirmButtonText:'确定',
          cancelButtonText:'取消',
          type:'warning'
        }).then(async ()=>{
          const{data:res}=await this.$http.delete(`categories/${id}`)
          if(res.meta.status!==200){
            return this.$message.error('删除失败')
          }
          this.$message.success('删除成功')
          this.getCateGoriesList()

        }).catch(()=>{

        })
      }



  },
};
</script>
<style lang="less" scoped>
.table-tree {
  margin-top: 15px;
}
.el-cascader{
  width: 100%;
}
</style>
